<?php
/**
 * 简化版轮播图管理API
 * 减少依赖，直接使用数据库连接
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'success' => true,
        'message' => $message,
        'data' => $data
    ]);
}

function error($message = '操作失败') {
    jsonResponse([
        'success' => false,
        'message' => $message,
        'data' => null
    ]);
}

// 获取请求数据
function getRequestData() {
    $input = file_get_contents('php://input');
    if (!empty($input)) {
        return json_decode($input, true);
    }
    return $_POST;
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'stats') {
                // 获取统计信息
                $sql = "SELECT 
                            COUNT(*) as total,
                            SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
                            SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive,
                            SUM(view_count) as total_views,
                            SUM(click_count) as total_clicks
                         FROM carousels";
                
                $stmt = $pdo->query($sql);
                $stats = $stmt->fetch(PDO::FETCH_ASSOC);
                
                // 今日点击统计
                $todayClicksSql = "SELECT COUNT(*) as today_clicks FROM carousel_clicks WHERE DATE(clicked_at) = CURDATE()";
                $todayStmt = $pdo->query($todayClicksSql);
                $todayClicks = $todayStmt->fetch(PDO::FETCH_ASSOC);
                $stats['today_clicks'] = $todayClicks['today_clicks'] ?? 0;
                
                success($stats);
                
            } elseif (!empty($id)) {
                // 获取单个轮播图
                $sql = "SELECT * FROM carousels WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->execute(['id' => $id]);
                $carousel = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$carousel) {
                    error('轮播图不存在');
                }
                
                success($carousel);
                
            } else {
                // 获取轮播图列表
                $page = max(1, intval($_GET['page'] ?? 1));
                $limit = min(50, max(1, intval($_GET['limit'] ?? 10)));
                $offset = ($page - 1) * $limit;
                
                $status = $_GET['status'] ?? '';
                $search = $_GET['search'] ?? '';
                
                $sql = "SELECT id, title, image_url, link_type, link_value, sort, status, 
                               view_count, click_count, created_at, updated_at 
                        FROM carousels 
                        WHERE 1=1";
                
                $params = [];
                
                if ($status) {
                    $sql .= " AND status = :status";
                    $params['status'] = $status;
                }
                
                if ($search) {
                    $sql .= " AND title LIKE :search";
                    $params['search'] = "%$search%";
                }
                
                $sql .= " ORDER BY sort ASC, id DESC LIMIT $limit OFFSET $offset";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                $carousels = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // 获取总数
                $countSql = str_replace("SELECT id, title, image_url, link_type, link_value, sort, status, view_count, click_count, created_at, updated_at", "SELECT COUNT(*) as total", $sql);
                $countSql = preg_replace('/ORDER BY.*LIMIT.*/', '', $countSql);
                $countStmt = $pdo->prepare($countSql);
                $countStmt->execute($params);
                $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
                
                success([
                    'list' => $carousels,
                    'pagination' => [
                        'page' => $page,
                        'limit' => $limit,
                        'total' => intval($total),
                        'pages' => ceil($total / $limit)
                    ]
                ]);
            }
            break;
            
        case 'POST':
            if ($action === 'sort') {
                // 批量更新排序
                $input = getRequestData();
                $items = $input['items'] ?? [];
                
                if (empty($items)) {
                    error('排序数据不能为空');
                }
                
                $pdo->beginTransaction();
                
                try {
                    foreach ($items as $item) {
                        $itemId = intval($item['id'] ?? 0);
                        $sort = intval($item['sort'] ?? 0);
                        
                        if ($itemId > 0) {
                            $sql = "UPDATE carousels SET sort = :sort, updated_at = NOW() WHERE id = :id";
                            $stmt = $pdo->prepare($sql);
                            $stmt->execute(['sort' => $sort, 'id' => $itemId]);
                        }
                    }
                    
                    $pdo->commit();
                    success(null, '排序更新成功');
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    error('更新排序失败: ' . $e->getMessage());
                }
                
            } else {
                // 创建轮播图
                $input = getRequestData();
                
                $title = trim($input['title'] ?? '');
                $imageUrl = trim($input['image_url'] ?? '');
                $linkType = $input['link_type'] ?? 'none';
                $linkValue = trim($input['link_value'] ?? '');
                $sort = intval($input['sort'] ?? 0);
                $status = $input['status'] ?? 'active';
                
                // 验证必填字段
                if (empty($title)) {
                    error('轮播图标题不能为空');
                }
                
                if (empty($imageUrl)) {
                    error('轮播图图片不能为空');
                }
                
                // 验证状态值
                if (!in_array($status, ['active', 'inactive'])) {
                    error('状态值无效');
                }
                
                // 验证链接类型
                if (!in_array($linkType, ['none', 'url', 'page', 'miniprogram'])) {
                    error('链接类型无效');
                }
                
                $sql = "INSERT INTO carousels (title, image_url, link_type, link_value, sort, status, view_count, click_count, created_at, updated_at) 
                        VALUES (:title, :image_url, :link_type, :link_value, :sort, :status, 0, 0, NOW(), NOW())";
                
                $stmt = $pdo->prepare($sql);
                $result = $stmt->execute([
                    'title' => $title,
                    'image_url' => $imageUrl,
                    'link_type' => $linkType,
                    'link_value' => $linkValue,
                    'sort' => $sort,
                    'status' => $status
                ]);
                
                if ($result) {
                    success(['id' => $pdo->lastInsertId()], '轮播图创建成功');
                } else {
                    error('轮播图创建失败');
                }
            }
            break;
            
        case 'PUT':
            // 更新轮播图
            if (empty($id)) {
                error('轮播图ID不能为空');
            }
            
            // 验证轮播图存在
            $checkSql = "SELECT id FROM carousels WHERE id = :id";
            $checkStmt = $pdo->prepare($checkSql);
            $checkStmt->execute(['id' => $id]);
            if (!$checkStmt->fetch()) {
                error('轮播图不存在');
            }
            
            $input = getRequestData();
            $updateData = ['updated_at' => 'NOW()'];
            $params = ['id' => $id];
            
            // 只更新提供的字段
            if (isset($input['title'])) {
                $title = trim($input['title']);
                if (empty($title)) {
                    error('轮播图标题不能为空');
                }
                $updateData['title'] = ':title';
                $params['title'] = $title;
            }
            
            if (isset($input['image_url'])) {
                $imageUrl = trim($input['image_url']);
                if (empty($imageUrl)) {
                    error('轮播图图片不能为空');
                }
                $updateData['image_url'] = ':image_url';
                $params['image_url'] = $imageUrl;
            }
            
            if (isset($input['link_type'])) {
                if (!in_array($input['link_type'], ['none', 'url', 'page', 'miniprogram'])) {
                    error('链接类型无效');
                }
                $updateData['link_type'] = ':link_type';
                $params['link_type'] = $input['link_type'];
            }
            
            if (isset($input['link_value'])) {
                $updateData['link_value'] = ':link_value';
                $params['link_value'] = trim($input['link_value']);
            }
            
            if (isset($input['sort'])) {
                $updateData['sort'] = ':sort';
                $params['sort'] = intval($input['sort']);
            }
            
            if (isset($input['status'])) {
                if (!in_array($input['status'], ['active', 'inactive'])) {
                    error('状态值无效');
                }
                $updateData['status'] = ':status';
                $params['status'] = $input['status'];
            }
            
            $setClause = [];
            foreach ($updateData as $field => $placeholder) {
                if ($field === 'updated_at') {
                    $setClause[] = "$field = NOW()";
                } else {
                    $setClause[] = "$field = $placeholder";
                }
            }
            
            $sql = "UPDATE carousels SET " . implode(', ', $setClause) . " WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute($params);
            
            if ($result) {
                success(null, '轮播图更新成功');
            } else {
                error('轮播图更新失败');
            }
            break;
            
        case 'DELETE':
            // 删除轮播图
            if (empty($id)) {
                error('轮播图ID不能为空');
            }
            
            // 验证轮播图存在
            $checkSql = "SELECT id FROM carousels WHERE id = :id";
            $checkStmt = $pdo->prepare($checkSql);
            $checkStmt->execute(['id' => $id]);
            if (!$checkStmt->fetch()) {
                error('轮播图不存在');
            }
            
            // 删除轮播图
            $sql = "DELETE FROM carousels WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute(['id' => $id]);
            
            if ($result) {
                // 同时删除相关的点击记录
                try {
                    $clickSql = "DELETE FROM carousel_clicks WHERE carousel_id = :id";
                    $clickStmt = $pdo->prepare($clickSql);
                    $clickStmt->execute(['id' => $id]);
                } catch (Exception $e) {
                    // 删除点击记录失败不影响主要操作
                }
                
                success(null, '轮播图删除成功');
            } else {
                error('轮播图删除失败');
            }
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage());
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage());
}
?>